import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
const ETH_ADDRESS = "0x0000000000000000000000000000000000000000";

const balanceSlice = createSlice({
    name: "balance",
    initialState: {
        TokenWallet: "0", // wei转换，字符串格式
        TokenExchange: "0",
        EtherWallet: "0",
        EtherExchange: "0"
    },
    reducers: {
        setTokenWallet: (state, action) => {
            state.TokenWallet = action.payload;
        },
        setTokenExchange: (state, action) => {
            state.TokenExchange = action.payload;
        },
        setEtherWallet: (state, action) => {
            state.EtherWallet = action.payload;
        },
        setEtherExchange: (state, action) => {
            state.EtherExchange = action.payload;
        },
    },
});

export const { setTokenWallet, setTokenExchange, setEtherWallet, setEtherExchange } = balanceSlice.actions;

export default balanceSlice.reducer;

export const loadBalanceData = createAsyncThunk("balance/fetchBalanceData", async (data, { dispatch }) => {
    const { web3, account, token, exchange } = data;

    // 获取钱包token
    const TokenWallet = await token.methods.balanceOf(account).call();
    dispatch(setTokenWallet(TokenWallet));

    // 获取交易所token
    console.log(token.options);
    const TokenExchange = await exchange.methods.balanceOf(token.options.address, account).call();
    dispatch(setTokenExchange(TokenExchange));

    // 获取钱包ether
    const EtherWallet = await web3.eth.getBalance(account);
    dispatch(setEtherWallet(EtherWallet));

    // 获取交易所ether
    const EtherExchange = await exchange.methods.balanceOf(ETH_ADDRESS, account).call();
    dispatch(setEtherExchange(EtherExchange));
});